package com.example.demo.controller;

import com.example.demo.model.Product;
import com.example.demo.service.CollectionService;
import com.example.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CollectionService collectionService;

    @RequestMapping("/all")
    public List<Product> getAllProducts() {
        // code to get all products from database
        return productService.getAllProducts();
    }

    @RequestMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable("id") String id) {
        return productService.getProductById(id).map(
                product -> ResponseEntity.ok().body(product)
        ).orElse(ResponseEntity.notFound().build());
    }

    @PostMapping("/add")
    public Product addProduct(@RequestBody Product product) {
        return productService.addProduct(product);
    }

    @PutMapping("/update/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
        return productService.getProductById(id).map(productUpdate -> {
            productUpdate.setName(product.getName());
            productUpdate.setDescription(product.getDescription());
            productUpdate.setPrice(product.getPrice());
            productUpdate.setQuantity(product.getQuantity());
            return ResponseEntity.ok(productService.updateProduct(id,product));

        }).orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("filter")
    public List<Product> filterProductByName(@RequestParam("name") String name)
    {
        System.out.println("filterProductByName " + name);
        return collectionService.findProductByName(name);
    }

    @GetMapping("filter/price/{price}")
    public List<Product> filterProductByPrice(@PathVariable("price") double price)
    {
        return collectionService.findProductByPrice(price);
    }
    @GetMapping("/filter/pricesBetween")
    public List<Product> filterProductByPriceBetween(@RequestParam("min") double min, @RequestParam("max") double max)
    {
        return collectionService.findProductByPriceBetween(min,max);
    }

}
